package com.lancoo.answer.view.fragment.readMatch

import android.content.Context
import android.os.Bundle
import android.view.View
import androidx.fragment.app.Fragment
import com.lancoo.answer.R
import com.lancoo.answer.component.InteractWebView
import com.lancoo.answer.databinding.EvFragmentCommonBinding
import com.lancoo.answer.model.AnswerConstant
import com.lancoo.answer.model.ConstantBean
import com.lancoo.answer.model.TaskState
import com.lancoo.answer.model.bean.Ques
import com.lancoo.answer.view.base.BaseVMFragment
import com.lancoo.answer.widget.SplitView
import com.rxjava.rxlife.ObservableLife
import com.rxjava.rxlife.RxLife
import io.reactivex.Observable
import io.reactivex.Single
import io.reactivex.android.schedulers.AndroidSchedulers
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.util.concurrent.TimeUnit

/**
 * Created by Dadong on 2021/12/13
 * Describe: 阅读匹配
 */
class ReadMatchFragment : BaseVMFragment<EvFragmentCommonBinding>() {

    private lateinit var ques: Ques
    private var typeIndex = 0
    private var quesIndex = 0
    private var defaultLoadIndex = 0
    private var currentSmallQueseIndex = 0
    private val TAG = "ReadMatchFragment"
    private lateinit var readMatchChildFragment: ReadMatchChildFragment
    private lateinit var convertView: View

    override fun getLayoutId(): Int {
        return R.layout.ev_fragment_common
    }

    companion object {
        fun loadFragment(typeIndex: Int, quesIndex: Int, defaultLoadIndex: Int): Fragment? {
            val mBundle = Bundle()
            mBundle.putInt(AnswerConstant.KEY_TYPEINDEX, typeIndex)
            mBundle.putInt(AnswerConstant.KEY_QUESINDEX, quesIndex)
            mBundle.putInt(AnswerConstant.KEY_LOADCHILDINDEX, defaultLoadIndex)
            val readMatchFragment = ReadMatchFragment()
            readMatchFragment.arguments = mBundle
            return readMatchFragment
        }
    }

    override fun initView(view: View) {
        convertView = view
        EventBus.getDefault().register(this)
    }

    override fun initData() {
        if (ConstantBean.constantExamBean == null) {
            return
        }
        val kindBeanList = ConstantBean.constantExamBean!!.TypeList
        typeIndex = requireArguments().getInt(AnswerConstant.KEY_TYPEINDEX)
        quesIndex = requireArguments().getInt(AnswerConstant.KEY_QUESINDEX)
        defaultLoadIndex = requireArguments().getInt(AnswerConstant.KEY_LOADCHILDINDEX)
        ques = kindBeanList!![typeIndex].QuesList!![quesIndex]
        mBinding.interactWv.setIsIndentation(ques.IsIndentQuesBody)
        mBinding.interactWv.setQues(ques)
        mBinding.interactWv.initWebView(
            requireActivity(),
            ques.QuesBody!!, object :InteractWebView.Callback{
                override fun clickCallback(position: String) {
                }

                override fun finishCallback() {
                    initLayout()
                    adjustFontSize()
                    if (ConstantBean.taskState == TaskState.TRAINING) {
                        Observable.timer(200, TimeUnit.MILLISECONDS) //必须加延时才能算准高度
                            .observeOn(AndroidSchedulers.mainThread())
                            .`as`<ObservableLife<Long>>(RxLife.`as`<Long>(this@ReadMatchFragment))
                            .subscribe { aLong: Long? ->
                                if (arguments == null) {
                                    return@subscribe
                                }
                                openPalette()
                            }
                    }
                }

            }
        )
        initAnswer()
    }

    private fun openPalette() {
        val sharedPreferences =
            requireContext().getSharedPreferences(AnswerConstant.SP_ANSWER_NAME, Context.MODE_PRIVATE)
        val openDash = sharedPreferences.getBoolean(AnswerConstant.SP_OPEN_DASH, false)
        if (openDash) {
            mBinding.interactWv.openPalette()
        } else {
            mBinding.interactWv.closePalette()
        }
    }

    private fun initAnswer() {
        readMatchChildFragment = ReadMatchChildFragment.loadFragment(
            typeIndex,
            quesIndex,
            defaultLoadIndex
        ) as ReadMatchChildFragment
        childFragmentManager
            .beginTransaction()
            .replace(mBinding.flAnswer.id, readMatchChildFragment, TAG)
            .commit()
    }

    fun setQues(ques: Ques) {
        this.ques = ques
    }

    /**
     * 获取当前大题下的小题序号
     * @return 小题序号
     */
    fun getCurrentSmallQueseIndex(): Int {
        return currentSmallQueseIndex
    }

    /**
     * 跳转到指定小题
     * @param childIndex 小题序号
     */
    fun jumpToAimChildFragment(childIndex: Int) {
        if (childFragmentManager != null &&
            mBinding != null
        ) {
            val fragment = childFragmentManager.findFragmentByTag(TAG)
            if (fragment is ReadMatchChildFragment) {
                fragment.setCurrentItem(childIndex)
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onGetPosition(position: Int?) {
        currentSmallQueseIndex = position!!
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }

    fun getChildIndex(): Int {
        return 0
    }

    fun adjustFontSize() {
        mBinding.interactWv.setFontSize()
        readMatchChildFragment.adjustFontSize()
    }

    fun initLayout() {
        if (convertView == null) {
            return
        }
        val splitView: SplitView = convertView!!.findViewById<SplitView>(R.id.split_view)
        Single.timer(250, TimeUnit.MILLISECONDS)
            .observeOn(AndroidSchedulers.mainThread())
            .`as`(RxLife.`as`(this))
            .subscribe({ splitView.initLayout(0.5f) }) { throwable: Throwable? -> }
    }

    fun markQuestion() {
        readMatchChildFragment.markQuestion()
    }
}